package com.juyu.miliao.common.dataSource.tool.distributeOperate;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.juyu.miliao.common.dataSource.key.DataSourceKey;

public class DistributeOperateProcessor {
	private static final Logger logger = LoggerFactory.getLogger(DistributeOperateProcessor.class);
	private final DataSourceKey dataSourceKey;
	private final List<Object> jobs = new ArrayList<>();
	private final DistributeResultHandler resultHandler;
	private final ExecutorService executor;
	
	public DistributeOperateProcessor(DataSourceKey dataSourceKey, DistributeResultHandler resultHandler, ExecutorService executor){
		this.dataSourceKey = dataSourceKey;
		this.resultHandler = resultHandler;
		this.executor = executor;
	}
	
	public void addJob(String key, ProceedingJoinPoint pjp, Object[] args){
		if(logger.isDebugEnabled())
			logger.debug("设置当前 dataSourceKey");
		dataSourceKey.set(key);
		if(logger.isDebugEnabled())
			logger.debug("设置当前 dataSourceKey 为：" + key);
		try{
			jobs.add(pjp.proceed(args));
		} catch (Throwable e) {
			throw new RuntimeException(e);
		}finally{
			dataSourceKey.remove();
			if(logger.isDebugEnabled())
				logger.debug("清空当前 dataSourceKey");
		}
	}
	
	public Object get(){
		return resultHandler.handle(jobs.stream());
	}
	
}
